package com.chuangke.monitor.service;

import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.chuangke.common.utils.IpUtils;
import com.chuangke.common.utils.NumberUtils;
import com.chuangke.monitor.model.Cpu;
import com.chuangke.monitor.model.Jvm;
import com.chuangke.monitor.model.Mem;
import com.chuangke.monitor.model.Server;
import com.chuangke.monitor.model.Sys;
import com.chuangke.monitor.model.SysFile;

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

@Service
public class ServerMonitorServer {

	private static final Logger logger = LoggerFactory.getLogger(ServerMonitorServer.class);

	public Server getServerInfo() {
		Server server = new Server();
		SystemInfo si = new SystemInfo();
		HardwareAbstractionLayer hal = si.getHardware();

		server.setCpu(getCpuInfo(hal.getProcessor()));

		server.setMem(getMemInfo(hal.getMemory()));

		server.setSys(getSysInfo());

		server.setJvm(getJvmInfo());

		server.setSysFiles(getSysFiles(si.getOperatingSystem()));

		return server;
	}

	/**
	 * 设置CPU信息
	 */
	private Cpu getCpuInfo(CentralProcessor processor) {
		Cpu cpu = new Cpu();
		try {
			// CPU信息
			long[] prevTicks = processor.getSystemCpuLoadTicks();
			Util.sleep(Server.OSHI_WAIT_SECOND);
			long[] ticks = processor.getSystemCpuLoadTicks();
			long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
			long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
			long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
			long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
			long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
			long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
			long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
			long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
			long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;

			cpu.setCpuNum(processor.getLogicalProcessorCount());
			cpu.setTotal(totalCpu);
			cpu.setSys(cSys);
			cpu.setUsed(user);
			cpu.setWait(iowait);
			cpu.setFree(idle);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return cpu;
	}

	/**
	 * 设置内存信息
	 */
	private Mem getMemInfo(GlobalMemory memory) {
		Mem mem = new Mem();
		try {
			mem.setTotal(memory.getTotal());
			mem.setUsed(memory.getTotal() - memory.getAvailable());
			mem.setFree(memory.getAvailable());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return mem;
	}

	/**
	 * 设置服务器信息
	 */
	private Sys getSysInfo() {
		Sys sys = new Sys();
		try {
			Properties props = System.getProperties();
			sys.setComputerName(IpUtils.getHostName());
			sys.setComputerIp(IpUtils.getHostIp());
			sys.setOsName(props.getProperty("os.name"));
			sys.setOsArch(props.getProperty("os.arch"));
			sys.setUserDir(props.getProperty("user.dir"));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return sys;
	}

	/**
	 * 设置Java虚拟机
	 */
	private Jvm getJvmInfo() {
		Jvm jvm = new Jvm();
		try {
			Properties props = System.getProperties();
			jvm.setTotal(Runtime.getRuntime().totalMemory());
			jvm.setMax(Runtime.getRuntime().maxMemory());
			jvm.setFree(Runtime.getRuntime().freeMemory());
			jvm.setVersion(props.getProperty("java.version"));
			jvm.setHome(props.getProperty("java.home"));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return jvm;
	}

	/**
	 * 设置磁盘信息
	 */
	private List<SysFile> getSysFiles(OperatingSystem os) {
		List<SysFile> sysFiles = new LinkedList<>();
		try {
			FileSystem fileSystem = os.getFileSystem();
			List<OSFileStore> fsArray = fileSystem.getFileStores();
			for (OSFileStore fs : fsArray) {
				long free = fs.getUsableSpace();
				long total = fs.getTotalSpace();
				long used = total - free;
				SysFile sysFile = new SysFile();
				sysFile.setDirName(fs.getMount());
				sysFile.setSysTypeName(fs.getType());
				sysFile.setTypeName(fs.getName());
				sysFile.setTotal(convertFileSize(total));
				sysFile.setFree(convertFileSize(free));
				sysFile.setUsed(convertFileSize(used));
				if (total != 0) {
					sysFile.setUsage(NumberUtils.mul(NumberUtils.div(used, total, 4), 100));
				}

				sysFiles.add(sysFile);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return sysFiles;
	}

	/**
	 * 字节转换
	 * 
	 * @param size 字节大小
	 * @return 转换后值
	 */
	public String convertFileSize(long size) {
		long kb = 1024;
		long mb = kb * 1024;
		long gb = mb * 1024;
		if (size >= gb) {
			return String.format("%.1f GB", (float) size / gb);
		} else if (size >= mb) {
			float f = (float) size / mb;
			return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
		} else if (size >= kb) {
			float f = (float) size / kb;
			return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
		} else {
			return String.format("%d B", size);
		}
	}
}
